<?php

namespace app\admin\framework\controller;

use app\common\model\User;
use support\Response;
use Webman\Captcha\CaptchaBuilder;
use app\common\service\UserService;

class PublicController
{
    
    private $noNeedLogin = ['login', 'captcha', 'logout'];
    
    /**
     * 登录
     * @return void
     */
    public function login(): Response
    {
        
        $username = request()->post('username', '');
        if (empty($username))
            return apiError('请填写用户名');
        
        $password = request()->post('password', '');
        if (empty($password))
            return apiError('请填写密码');
        
        $captcha = request()->post('captcha', '');
        if (empty($captcha))
            return apiError('请填写验证码');
        
        $captchaSession = request()->session()->get('captcha');
        if (strtoupper($captcha) !== strtoupper($captchaSession))
            return apiError('请填写正确验证码');
        
        $result = User::where('username|mobile', $username)->find();
        
        // echo password_hash('admin123', PASSWORD_DEFAULT) . PHP_EOL;
        
        if (empty($result)) {
            return apiError('账号或密码错误~');
        } else {
            if (password_verify($password, $result->password)) {
                if ($result->id !== 1 && $result->status !== 1) {
                    return apiError('该账号当前被禁用');
                }
                $result->last_login_time = date('Y-m-d H:i:s');
                $result->last_login_ip = request()->getRealIp();
                $result->token = md5(uniqid()) . md5(uniqid());
                $result->save();
                $token = UserService::generateToken($result->id);
                return apiSuccess('登录成功', ['token' => $token]);
            }
            return apiError('账号或密码错误~');
        }
        
        
    }
    
    /**
     * 退出登录
     */
    public function logout()
    {
        request()->session()->delete("ADMIN_ID");
        request()->session()->delete("admin");
        return redirect('/admin');
    }
    
    /**
     * 输出验证码图像
     */
    public function captcha()
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder();
        // 生成验证码
        $builder->build(width: 120);
        // 将验证码的值存储到session中
        request()->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        $img_content = $builder->get();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }
    
    
}